package com.xiaoma.tpo.schedule;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.xiaoma.tpo.domain.Activity;
import com.xiaoma.tpo.service.ActivityService;
import com.xiaoma.tpo.utils.baidupush.AndroidPushMsg;
import com.xiaoma.tpo.utils.baidupush.BDPush;
import com.xiaoma.tpo.utils.baidupush.IOSPushMsg;
import com.xiaoma.verbal.utils.DateUtil;

/**
 * 活动定时任务
 * 
 * @author 1
 * 
 */
@Component("activityTask")
@Lazy(false)
public class ActivityListTask {

	@Autowired
	private ActivityService activityService;

	@Scheduled(cron = "0 0/1 * * * ?")
	public void work() {
		String dateStr = DateUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm");

		List<Activity> list;
		try {
			list = activityService.findByStartDate(DateUtil.strToDate(dateStr,
					"yyyy-MM-dd HH:mm"));
			if (list.size() > 0) {
				for (Activity activity : list) {
					androidBroadcastMessage(activity);
					iosBroadcastMessage(activity);
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
			System.out.println("时间转换异常");
		}

	}

	/**
	 * 活动安卓广播
	 * @param activity
	 */
	private void androidBroadcastMessage(Activity activity) {
	    AndroidPushMsg androidMsg = new AndroidPushMsg();
        androidMsg.setTitle("托福21天");
        androidMsg.setDescription(activity.getTitle());
        JSONObject custom = new JSONObject();
        custom.put("flag", 1);
        custom.put("activityId", activity.getId());
        androidMsg.setCustomContent(custom);
        try {
            BDPush.androidPush2All(androidMsg);
        } catch (PushClientException | PushServerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
	}
	
	/**
     * 活动ios广播
     * @param activity
     */
	private void iosBroadcastMessage(Activity activity) {
	    IOSPushMsg msg = new IOSPushMsg();
        msg.setTitle(activity.getTitle());
        Map<String, Object> content = new HashMap<String, Object>();
        content.put("flag", 1);
        content.put("activityId", activity.getId());
        msg.setContent(content);
        try {
            BDPush.iosPush2All(msg);
        } catch (PushClientException | PushServerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
	}
	
}
